package com.ubing.boot.notesforjava.test.file;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class StringToByteBuffer {

    public static void main(String[] args) {
        String str = "hello";
        byte[] bytes = str.getBytes();
        System.out.println(bytes.length);
        // 11
        System.out.println(bytes[0]);
        // 104
        System.out.println(bytes[1]);
        // 101
        System.out.println(bytes[2]);
        // 108
        System.out.println(bytes[3]);
        // 108
        System.out.println(bytes[4]);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put(bytes);
        buffer.flip();// 将buffer指针位置 置为0
        while (buffer.hasRemaining()){ // 是否有剩余数据
            byte b = buffer.get();
            System.out.println((char) b);
        }
        buffer.flip();
        System.out.println("+++++++++++++++++++++++");
        //Charset
        ByteBuffer hello = StandardCharsets.UTF_8.encode("hello1");
        while (hello.hasRemaining()){ // 是否有剩余数据
            byte b = hello.get();
            System.out.println((char) b);
        }
        hello.flip();
        System.out.println("+++++++++++++++++++++++");
        // wrap
        ByteBuffer wrap = ByteBuffer.wrap("hello2".getBytes());
        while (wrap.hasRemaining()){ // 是否有剩余数据
            byte b = wrap.get();
            System.out.println((char) b);
        }
        wrap.flip();
        String string = StandardCharsets.UTF_8.decode(wrap).toString();
        System.out.println(string);
    }
}
